package com.ilop.sthome.ui.activity.main;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.IBinder;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.GravityCompat;
import androidx.viewpager.widget.ViewPager;
import androidx.drawerlayout.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.common.utils.LiveDataBus;
import com.example.common.utils.SpUtil;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.mvp.contract.mine.MainContract;
import com.ilop.sthome.mvp.present.mine.MainPresenter;
import com.ilop.sthome.service.SiterService;
import com.ilop.sthome.ui.activity.mine.AboutActivity;
import com.ilop.sthome.ui.activity.mine.AssessActivity;
import com.ilop.sthome.ui.activity.mine.HeadPortraitActivity;
import com.ilop.sthome.ui.activity.mine.InstructionActivity;
import com.ilop.sthome.ui.activity.mine.PersonalActivity;
import com.ilop.sthome.ui.activity.mine.SetUpActivity;
import com.example.common.base.MyPagerAdapter;
import com.ilop.sthome.utils.greenDao.utils.DeviceDaoUtil;
import com.ilop.sthome.utils.greenDao.utils.RoomDaoUtil;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivityMainBinding;

/**
 * @author skygge
 * @Date on 2019-09-25.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：主页面
 */
public class MainActivity extends ContainLoginActivity<MainPresenter, ActivityMainBinding> implements MainContract.IView {

    private long lastBackKeyDownTick = 0;
    private static final long MAX_DOUBLE_BACK_DURATION = 2000;

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initPresent() {
        super.initPresent();
        mPresent = new MainPresenter(mContext);
    }

    @Override
    protected void initView() {
        super.initView();
        mDBind.drawerLayout.addDrawerListener(drawerListener);
        mDBind.drawerLayout.setScrimColor(Color.TRANSPARENT);
        MyPagerAdapter mAdapter = new MyPagerAdapter(getSupportFragmentManager());
        mAdapter.setFragment(mPresent.getFragmentList());
        mDBind.mainViewPage.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
        super.initData();
        try{
            int mRoomSize = RoomDaoUtil.getInstance().getRoomDao().queryAll().size();
            if (mRoomSize == 0){
                RoomDaoUtil.getInstance().insertDefaultRoom(mContext);
            }
        }catch (Exception e){
            e.printStackTrace();
            System.exit(0);
        }
        boolean isNewVersion = SpUtil.getBoolean(mContext, CommonId.KEY_NEW_VERSION);
        if (!isNewVersion){
            DeviceDaoUtil.getInstance().getDeviceDao().deleteAll();
            SpUtil.putBoolean(mContext, CommonId.KEY_NEW_VERSION, true);
        }
        mPresent.refreshRequestUserInfo();
    }

    @Override
    protected void initDataBus() {
        super.initDataBus();
        LiveDataBus.get().with(CommonId.OPEN_MENU, Integer.class).observe(this, integer -> mDBind.drawerLayout.openDrawer(GravityCompat.START));
        LiveDataBus.get().with(CommonId.KEY_MESSAGE, String.class).observe(this, s -> {
            if (s != null){
                mDBind.mainViewPage.setCurrentItem(2);
                mDBind.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                if (s.contains("iotId")){ // 告警信息
                    LiveDataBus.get().with(CommonId.KEY_MESSAGE_TYPE).setValue(1);
                }else { //分享消息
                    LiveDataBus.get().with(CommonId.KEY_MESSAGE_TYPE).setValue(2);
                }
            }
        });
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.mainPerson.setOnClickListener(view -> {
            Intent intent = new Intent(mContext, PersonalActivity.class);
            startActivityForResult(intent , 0x111);
        });

        mDBind.mainAbout.setOnClickListener(view -> skipAnotherActivity(AboutActivity.class));

        mDBind.mainUserImg.setOnClickListener(view -> skipAnotherActivity(HeadPortraitActivity.class));

        mDBind.mainInstructions.setOnClickListener(view -> skipAnotherActivity(InstructionActivity.class));

        mDBind.mainSetting.setOnClickListener(view -> skipAnotherActivity( SetUpActivity.class));

        mDBind.mainAssess.setOnClickListener(view -> skipAnotherActivity(AssessActivity.class));

        mDBind.mainLoginOut.setOnClickListener(view -> mPresent.onLoginOut());

        mDBind.mainNavigation.setOnNavigationItemSelectedListener(menuItem -> {
            switch (menuItem.getItemId()){
                case R.id.item_main_device:
                    mDBind.mainViewPage.setCurrentItem(0);
                    mDBind.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                    return true;
                case R.id.item_main_scene:
                    mDBind.mainViewPage.setCurrentItem(1);
                    mDBind.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                    return true;
                case R.id.item_main_message:
                    mDBind.mainViewPage.setCurrentItem(2);
                    mDBind.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                    return true;
            }
            return false;
        });

        mDBind.mainViewPage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                mDBind.mainNavigation.getMenu().getItem(i).setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x111 && resultCode == 1){
            mPresent.refreshRequestUserInfo();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent bindIntent = new Intent(this, SiterService.class);
        bindService(bindIntent, mConnection, BIND_AUTO_CREATE);
    }

    @Override
    public void showLoginName(String loginName) {
        mDBind.mainLoginName.setText(loginName);
    }

    @Override
    public void showNickName(String nickname) {
        if (nickname!=null){
            mDBind.mainNickName.setText(nickname);
        }else {
            mDBind.mainNickName.setVisibility(View.GONE);
        }
    }

    @Override
    public void showUserImage(String uri) {
        if (!TextUtils.isEmpty(uri)){
            Glide.with(mContext)
                    .load(uri)
                    .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
                    .apply(RequestOptions.skipMemoryCacheOf(true))
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(mDBind.mainUserImg);
        }else {
            Glide.with(mContext)
                    .load(R.mipmap.head_default)
                    .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
                    .apply(RequestOptions.skipMemoryCacheOf(true))
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(mDBind.mainUserImg);
        }
    }

    @Override
    public void showToastMsg(String msg) {
        showToast(msg);
    }

    @Override
    public void loginOut() {
        if (mDBind.drawerLayout.isDrawerOpen(GravityCompat.START)){
            mDBind.drawerLayout.closeDrawer(GravityCompat.START);
        }
        onLoginOut();
    }

    /**
     * DrawerListener
     */
    DrawerLayout.DrawerListener drawerListener = new DrawerLayout.DrawerListener() {
        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            // 得到contentView 实现侧滑界面出现后主界面向右平移避免侧滑界面遮住主界面
            View content = mDBind.drawerLayout.getChildAt(0);
            int offset = (int) (drawerView.getWidth() * slideOffset);
            content.setTranslationX(offset);
        }

        @Override
        public void onDrawerOpened(@NonNull View drawerView) {
            //打开侧滑界面触发
        }

        @Override
        public void onDrawerClosed(@NonNull View drawerView) {
            //关闭侧滑界面触发
        }

        @Override
        public void onDrawerStateChanged(int newState) {
            //状态改变时触发
        }
    };

    @Override
    public void onBackPressed() {
        if (mDBind.drawerLayout.isDrawerOpen(GravityCompat.START)){
            mDBind.drawerLayout.closeDrawer(GravityCompat.START);
            return;
        }
        long currentTick = System.currentTimeMillis();
        if (currentTick - lastBackKeyDownTick > MAX_DOUBLE_BACK_DURATION) {
            showToast(getString(R.string.again_exist_app));
            lastBackKeyDownTick = currentTick;
        } else {
            finish();
        }
    }
    
    @Override
    protected void onDestroy() {
        SpUtil.putInt(mContext, CommonId.UPDATE_ASSESS_RING, 0);
        unbindService(mConnection);
        super.onDestroy();
    }
}
